import axios from "axios"
import { ElMessage } from "element-plus"
import { getToken } from "./utils"

// 创建axios实例
const service = axios.create({
  baseURL: "http://localhost:8080/api", // API的base_url
  timeout: 15000, // 请求超时时间
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
})

// 请求拦截器
service.interceptors.request.use(
  (config: any) => {
    // 在请求发送之前做一些处理，比如添加token
    const token = getToken()
    if (token) {
      config.headers = {
        ...config.headers,
        Authorization: `Bearer ${token}`,
      }
    }
    return config
  },
  (error) => {
    console.error("请求错误:", error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: any) => {
    const res = response.data
    // 这里可以根据后端的数据结构进行相应的处理
    if (res.code === 200) {
      return res
    } else {
      ElMessage.error("请求失败")
      return Promise.reject(new Error(res.message || "请求失败"))
    }
  },
  (error) => {
    if (error?.response?.data?.msg) {
      console.error(error?.response?.data?.msg)
    } else {
      ElMessage.error("服务器异常")
    }
    return Promise.reject(error)
  }
)

// 封装GET请求
export const get = (url: string, params?: any) => {
  return service.get(url, { params })
}

// 封装POST请求
export const post = (url: string, data?: any) => {
  return service.post(url, data)
}

// 封装PUT请求
export const put = (url: string, data?: any) => {
  return service.put(url, data)
}

// 封装DELETE请求
export const del = (url: string) => {
  return service.delete(url)
}

export default service
